import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluent_ui/fluent_ui.dart' hide IconButton;
import 'package:flutter/cupertino.dart' show CupertinoIcons;
import 'package:flutter/material.dart' hide ListTile, Card, Colors;
import 'package:fnos_tv_desktop/core/api/bean/media_info_result.dart';
import 'package:fnos_tv_desktop/view/main/home/scroll_control.dart';
import 'package:provider/provider.dart';

import '../../../application/nav.dart';
import '../../../core/api/api.dart';
import '../main_page_model.dart';

class PlayListRow extends StatefulWidget {
  const PlayListRow({super.key});

  @override
  State<PlayListRow> createState() => _PlayListRowState();
}

class _PlayListRowState extends State<PlayListRow> {
  final scrollController = ScrollController();

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final model = context.watch<MainPageModel>();
    return StreamBuilder(
      stream: model.playList,
      builder: (context, asyncSnapshot) {
        if (asyncSnapshot.hasError) {
          return Container();
        }
        if (asyncSnapshot.connectionState != ConnectionState.active) {
          return Container();
        }
        final list = asyncSnapshot.data!;
        if (list.isEmpty) {
          return Container();
        }
        return Column(
          children: [
            ListTile(title: Text('继续播放')),
            SizedBox(
              height: 235,
              child: ScrollControl(
                controller: scrollController,
                child: ListView.builder(
                  controller: scrollController,
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  scrollDirection: Axis.horizontal,
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    final db = list[index];
                    return PlayListItem(info: db);
                  },
                ),
              ),
            ),
          ],
        );
      },
    );
  }
}

class PlayListItem extends StatefulWidget {
  final MediaInfoResult info;

  const PlayListItem({super.key, required this.info});

  @override
  State<PlayListItem> createState() => _PlayListItemState();
}

class _PlayListItemState extends State<PlayListItem> {
  late final title = getTitle();
  late final subtitle = getSubtitle();
  bool isHover = false;
  final api = Api();

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (event) {
        setState(() {
          isHover = true;
        });
      },
      onExit: (event) {
        setState(() {
          isHover = false;
        });
      },
      child: Container(
        margin: const EdgeInsets.all(4),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            hoverColor: Colors.transparent,
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            borderRadius: BorderRadius.circular(12),
            onTap: () {
              context.read<MainPageModel>().goToDetails(widget.info);
            },
            child: AspectRatio(
              aspectRatio: 1.37,
              child: SizedBox(
                width: 306,
                child: Stack(
                  children: [
                    Column(
                      children: [
                        Expanded(
                          child: Card(
                            padding: EdgeInsets.zero,
                            borderColor: FluentTheme.of(context).shadowColor,
                            borderRadius: BorderRadius.circular(12),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(12),
                              child: Stack(
                                fit: StackFit.expand,
                                children: [
                                  if (widget.info.poster != null)
                                    CachedNetworkImage(
                                      imageUrl: api.imageUrl(
                                        widget.info.poster!,
                                      ),
                                      fit: BoxFit.cover,
                                      errorWidget: (context, url, error) =>
                                          Center(
                                            child: const Icon(
                                              FluentIcons.error,
                                            ),
                                          ),
                                    ),
                                  Align(
                                    alignment: Alignment.bottomCenter,
                                    child: Container(
                                      constraints: BoxConstraints.expand(),
                                      child: ProgressBar(
                                        value:
                                            100.0 *
                                            widget.info.ts /
                                            widget.info.duration,
                                        backgroundColor: Colors.transparent,
                                      ),
                                    ),
                                  ),
                                  Stack(
                                    children: [
                                      AnimatedContainer(
                                        duration: const Duration(
                                          milliseconds: 200,
                                        ),
                                        decoration: BoxDecoration(
                                          color: isHover
                                              ? Colors.black.withValues(
                                                  alpha: 0.6,
                                                )
                                              : null,
                                        ),
                                      ),
                                      if (isHover)
                                        Center(
                                          child: IconButton(
                                            iconSize: 50,
                                            onPressed: () {
                                              Nav.goToPlay(widget.info);
                                            },
                                            icon: Icon(
                                              CupertinoIcons.play_circle,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      if (isHover)
                                        Align(
                                          alignment: Alignment.bottomRight,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,

                                            children: [
                                              IconButton(
                                                icon: Icon(Icons.check),
                                                onPressed: () {},
                                              ),
                                              IconButton(
                                                icon: Icon(
                                                  Icons.favorite,
                                                  color:
                                                      widget.info.isFavorite ==
                                                          1
                                                      ? Colors.red
                                                      : null,
                                                ),
                                                onPressed: () {},
                                              ),
                                              IconButton(
                                                icon: Icon(Icons.more_horiz),
                                                onPressed: () {},
                                              ),
                                            ],
                                          ),
                                        ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.all(8),
                          child: Column(
                            children: [
                              Text(
                                title,
                                style: isHover
                                    ? FluentTheme.of(
                                        context,
                                      ).typography.body!.copyWith(
                                        color: FluentTheme.of(
                                          context,
                                        ).accentColor,
                                      )
                                    : FluentTheme.of(context).typography.body,
                                maxLines: 1,
                              ),
                              Text(
                                subtitle,
                                style: FluentTheme.of(context)
                                    .typography
                                    .caption!
                                    .copyWith(
                                      color: FluentTheme.of(
                                        context,
                                      ).inactiveColor.withValues(alpha: 0.6),
                                    ),
                                maxLines: 1,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  String getTitle() {
    switch (widget.info.type) {
      case 'Movie':
        return widget.info.title;
      case 'Episode':
        return widget.info.tvTitle;
      default:
        return '';
    }
  }

  String getSubtitle() {
    switch (widget.info.type) {
      case 'Movie':
        return '电影';
      case 'Episode':
        if (widget.info.seasonNumber > 0 && widget.info.episodeNumber > 0) {
          return '第${widget.info.seasonNumber}季·第${widget.info.episodeNumber}集';
        }
        return '第${widget.info.episodeNumber}集';
      default:
        return '';
    }
  }
}
